package edu.fdzc.learn.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import edu.fdzc.learn.entity.ExamQuestion;
import edu.fdzc.learn.entity.Exam;
import edu.fdzc.learn.entity.vo.*;
import edu.fdzc.learn.exception.ExamException;
import edu.fdzc.learn.result.ResponseEnum;
import edu.fdzc.learn.service.ExamQuestionService;
import edu.fdzc.learn.service.ExamService;
import edu.fdzc.learn.service.ExamSubmissionService;
import edu.fdzc.learn.utils.ResultVO;
import edu.fdzc.learn.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 考试系统控制器
 */
@RestController
@RequestMapping("/exam")
public class ExamController {

    @Autowired
    private ExamService examService;

    @Autowired
    private ExamQuestionService examQuestionService;

    @Autowired
    private ExamSubmissionService examSubmissionService;

    @GetMapping("/detail/{examId}")
    public ResultVO<ExamDetailVO> getExamDetail(@PathVariable("examId") Long examId) {
        // 1. 获取考试基本信息
        Exam exam = examService.getById(examId);
        if (exam == null) {
            throw new ExamException(ResponseEnum.EXAM_NOT_EXIST);
        }

        // 2. 构建详情VO
        ExamDetailVO detailVO = new ExamDetailVO();
        BeanUtils.copyProperties(exam, detailVO);

        // 3. 获取题目列表
        List<ExamQuestionVO> questionVOS = examQuestionService.getQuestionsByExam(examId);

        detailVO.setQuestions(questionVOS);
        return ResultVOUtil.success(detailVO);
    }

    /**
     * 提交考试答案


    /**
     * 获取考试结果
     */
    @GetMapping("/result/{submissionId}")
    public ResultVO<ExamResultVO> getExamResult(@PathVariable("submissionId") Long submissionId) {
        ExamResultVO resultVO = examSubmissionService.getExamResult(submissionId);
        if (resultVO == null) {
            throw new ExamException(ResponseEnum.RESULT_NOT_FOUND);
        }
        return ResultVOUtil.success(resultVO);
    }

    /**
     * 创建新考试
     */
    @PostMapping("/create")
    public ResultVO<Long> createExam(@RequestBody ExamCreateVO createVO) {
        Exam exam = new Exam();
        BeanUtils.copyProperties(createVO, exam);
        examService.save(exam);
        return ResultVOUtil.success(exam.getId());
    }

    /**
     * 添加考试题目
     */
    @PostMapping("/question/add/{examId}")
    public ResultVO<Boolean> addQuestion(@PathVariable("examId") Long examId,
                                         @RequestBody ExamQuestionVO questionVO) {
        ExamQuestion question = new ExamQuestion();
        BeanUtils.copyProperties(questionVO, question);
        question.setExamId(examId);
        return ResultVOUtil.success(examQuestionService.save(question));
    }
}